import { _decorator } from 'cc'
import { EntityManager } from '../../Base/EntityManager'
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM } from '../../Enum'
import EventManager from '../../Runtime/EventManager'
import DataManager from '../../Runtime/DataManager'
import { DoorStateMachine } from './DoorStateMachine'
import { IEntity } from '../../Levels'

const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = DoorManager
 * DateTime = Thu Jul 21 2022 19:34:26 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = DoorManager.ts
 * FileBasenameNoExtension = DoorManager
 * URL = db://assets/Scripts/Door/DoorManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('DoorManager')
export class DoorManager extends EntityManager {
  async init(params: IEntity) {
    this.fsm = this.addComponent(DoorStateMachine)
    await this.fsm.init()

    super.init(params)
    EventManager.Instance.on(EVENT_ENUM.DOOR_OPEN, this.onOpen, this)
  }

  // 解绑事件
  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.DOOR_OPEN, this.onOpen)
  }
  onOpen() {
    // 门还在,所有NPC都已经死亡，就让门消失
    if (
      this.state !== ENTITY_STATE_ENUM.DEATH &&
      DataManager.Instance.enemies.every(enemy => enemy.state === ENTITY_STATE_ENUM.DEATH)
    )
      this.state = ENTITY_STATE_ENUM.DEATH
  }
}
